package dicttypelogic

import (
	"context"

	"go-zero-admin/apps/system/cmd/rpc/internal/svc"
	"go-zero-admin/apps/system/cmd/rpc/syspb"
	"go-zero-admin/apps/system/model"
	"go-zero-admin/pkg/tool"
	"go-zero-admin/pkg/xerr"

	"github.com/jinzhu/copier"
	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type AddDictTypeLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
	isExDictTypeLogic *IsExDictTypeLogic
}

func NewAddDictTypeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddDictTypeLogic {
	return &AddDictTypeLogic{
		ctx:               ctx,
		svcCtx:            svcCtx,
		Logger:            logx.WithContext(ctx),
		isExDictTypeLogic: NewIsExDictTypeLogic(ctx, svcCtx),
	}
}

func (l *AddDictTypeLogic) AddDictType(in *syspb.AddDictTypeReq) (*syspb.AddDictTypeResp, error) {
	dictType := in.GetParams()
	if dictType == nil || dictType.GetDictName() == "" || dictType.GetDictType() == "" ||
		dictType.GetCreateUser() == "" || dictType.GetUpdateUser() == "" {
		return nil, errors.Wrapf(xerr.NewErrMsg("新增字典类型失败：参数缺失"),
			tool.GetErrMsgFormat("insert dictType"), "params is not existed", in)
	}

	// 校验字典类型是否重复
	resp, err := l.isExDictTypeLogic.IsExDictType(&syspb.IsExDictTypeReq{
		DictType: dictType.GetDictType(),
	})
	if err != nil {
		return nil, err
	}
	if resp.GetIsExist() {
		return nil, errors.Wrapf(xerr.NewErrMsg("新增字典类型失败：字典类型已存在"),
			tool.GetErrMsgFormat("insert dictType"), "dict type is existed", in)
	}

	// 数据转换
	var data model.SysDictType
	_ = copier.Copy(&data, in.GetParams())

	// 保存
	_, err = l.svcCtx.SysDictTypeModel.InsertEx(l.ctx, nil, []*model.SysDictType{&data})
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DbError), tool.GetErrMsgFormat("insert dictType"), err, in)
	}

	return &syspb.AddDictTypeResp{}, nil
}
